//
//  RGLoginWithPassViewModel.m
//  RedGrass
//
//  Created by wukong on 2019/1/2.
//  Copyright © 2019年 hongcaosp. All rights reserved.
//

#import "RGLoginWithPassViewModel.h"
#import "HttpRequest.h"

@interface RGLoginWithPassViewModel()

@property (weak, nonatomic) id<RGLoginWithPassViewProtocol> protocol;

@end

@implementation RGLoginWithPassViewModel

-(instancetype) initWithProtocol:(id<RGLoginWithPassViewProtocol>)protocol{
    if(self = [super init]){
        self.protocol = protocol;
    }
    return self;
}

-(void) loginWithPassword:(NSString *)pass phone:(NSString *)phone{
    AA_WEAK_MAKE(self) weakSelf = self;
    [self.protocol showLoading:@"正在登陆"];
    HttpRequest *quest = [HttpRequest buildRequest:@"/api/userLogin"];
    NSDictionary *params = @{@"mobile":SafeStr(phone),
                             @"password":SafeStr(pass),
                             @"type":@(1)
                             };
    [quest post:params success:^(id data) {
        [weakSelf.protocol dismissLoading];
        NSDictionary *dic = [data objectForKey:@"userInfo"];
        if([dic count]){
            NSError *error;
            RGUserInfoModel *user = [[RGUserInfoModel alloc]initWithDictionary:dic error:&error];
            if(error == nil){
                [RGUserInfoModel storeUserInfo:user];
                if([weakSelf.protocol respondsToSelector:@selector(loginWithPasswordSuccess)]){
                    [weakSelf.protocol loginWithPasswordSuccess];
                }
            }else{
                [weakSelf.protocol showTextMessageWithMessage:@"登录失败"];
            }
        }else{
            [weakSelf.protocol showTextMessageWithMessage:@"登录失败"];
        }
       
    } fail:^(NSInteger code, NSString *message) {
        [weakSelf.protocol showTextMessageWithMessage:message];
    }];
}

@end
